package com.cndcare.msc.netty.controller;

import com.cndcare.msc.netty.bean.PcBean;
import com.cndcare.msc.netty.dao.jpa.PcBeanJpa;
import com.cndcare.msc.netty.vo.SearchVo;
import com.cndcare.msc.service.NettyService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/manage")
public class NettyController {

    @Autowired
    private NettyService nettyService;
    @Value("${server.domain}")
    private String serverDomain;
    @Autowired
    private PcBeanJpa pcBeanJpa;

    @RequestMapping("/index")
    public String index(Map<String, Object> map) {

        map.put("statsDicMap", PcBean.statsDicMap);
        map.put("infoStatusMap", PcBean.infoStatusMap);
        map.put("serverDomain", serverDomain);

        return "netty/index";
    }

    @RequestMapping("/pagePc")
    @ResponseBody
    public PageInfo<PcBean> pagePc(
            @RequestParam(value = "pn", defaultValue = "1") Integer pn,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            SearchVo searchVo
    ) {
        return nettyService.listPcByParams(pn, pageSize, searchVo);
    }

    @RequestMapping("/listDangerPc")
    @ResponseBody
    public List<PcBean> listDangerPc() {

        return pcBeanJpa.findByStatus(PcBean.DANGER);
    }

    @RequestMapping("/calcPc")
    @ResponseBody
    public Map<String, Object> calcPc(
    ) {
        Map<String, Object> jsonMap = new HashMap<>();

        try {
            jsonMap.put("calcPc", nettyService.calcPc());
            jsonMap.put("flag", true);
        } catch (Exception e) {
            e.printStackTrace();
            jsonMap.put("flag", false);
            jsonMap.put("errorMsg", e.getMessage());
        }

        return jsonMap;
    }

    @RequestMapping("/refreshStatus")
    @ResponseBody
    public String refreshStatus() {
        nettyService.refreshPc();

        return "SUC";
    }

    @RequestMapping("/handleAlarm")
    @ResponseBody
    public Map<String, Object> handleAlarm(
            @RequestParam("mac") String mac,
            @RequestParam("type") String type
    ) {
        Map<String, Object> jsonMap = new HashMap<>();

        try {
            nettyService.handleAlarm(mac, type);

            jsonMap.put("flag", true);
        } catch (Exception e) {
            e.printStackTrace();
            jsonMap.put("flag", false);
            jsonMap.put("errorMsg", e.getMessage());
        }

        return jsonMap;
    }

}
